<?php
namespace App\DBs;

use App\DBs\BaseDB;
use Illuminate\Support\Facades\DB;

class AdminDB extends BaseDB
{
    /**
     * 管理员
     * name 管理员昵称
     * genre 管理员类型：1开发者，2管理员，3测试，
     * password 登陆密码
     * head 管理员头像
     */

    protected $table = 'admin';
    protected $tableLog = 'admin_log';

    public function __construct()
    {
        parent::__construct();
    }

    public function getGenres()
    {
        return array(
            1 => '开发者', '管理员', '测试',
        );
    }

    /**
     * 管理员列表
     */
    public function getAdminList()
    {
        $admins = DB::table($this->table)
//            ->select(['id', 'name', 'genre', 'created_at'])
            ->orderBy('id','desc')->get();
        if (!count($admins)) {
            return array('code'=>-2, 'msg'=>'没有管理员');
        }
        $dataArr = array();
        foreach ($admins as $admin) {
            $dataArr[] = $this->getArrByObj($admin);
        }
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 获取管理员
     */
    public function getOne($adminId)
    {
        $adminOne = DB::table($this->table)->where('id',$adminId)->first();
        if (!$adminOne) {
            return array('code'=>-1, 'msg'=>'管理员不存在');
        }
        $dataArr = array(
            'adminId' => $adminOne->id,
            'adminName' => $adminOne->name,
            'genre' => $adminOne->genre,
            'password' => $adminOne->password,
            'head' => $adminOne->head,
        );
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 新增管理员
     */
    public function setAdminAdd($name,$genre)
    {
        $adminOne = DB::table($this->table)->where('name',$name)
            ->orderBy('id','desc')->first();
        if ($adminOne) {
            if ($adminOne->genre!=$genre) {
                return array('code'=>-3, 'msg'=>'管理员类型错误');
            }
            return array('code'=>-2, 'msg'=>'管理员已存在');
        }
        $pwd = md5('123456');  //默认密码MD5加密
        //开启事务
        DB::beginTransaction();
        try {
            $lastId = DB::table($this->table)->insertGetId([
                'name' => $name,
                'genre' => $genre,
                'password' => $pwd,
                'created_at' => time(),
            ]);
            $dataArr = array(
                'lastId' => $lastId,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 通过adminID，获取管理员
     */
    public function getAdminOne($adminId)
    {
        $adminOne = DB::table($this->table)->where('id',$adminId)->first();
        if (!$adminOne) {
            return array('code'=>-1, 'msg'=>'管理员不存在');
        }
        $dataArr = $this->getArrByObj($adminOne);
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 通过adminName，获取管理员
     */
    public function getAdminByName($adminName,$pwd)
    {
        $adminOne = DB::table($this->table)->where('name',$adminName)->first();
        if (!$adminOne) {
            return array('code'=>-1, 'msg'=>'管理员不存在');
        }
        $pwd2 = md5($pwd);
        if ($adminOne->password != $pwd2) {
            return array('code'=>-2, 'msg'=>'管理员密码错误');
        }
        $dataArr = $this->getArrByObj($adminOne);
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 通过ADMINID，获取TOKEN
     */
    public function setTokenByAdminid($adminId)
    {
        $token = $this->getRandStr(rand(60,80));
        $adminLog = DB::table($this->tableLog)
//            ->where('admin',$adminId)
            ->where('token',$token)
            ->orderBy('id','desc')->first();
        if ($adminLog && $adminLog->token!=$token) {
            $token = $this->setTokenByAdminid($adminId);
        }
        $lastId = DB::table($this->tableLog)->insertGetId([
            'admin' => $adminId,
            'token' => $token,
            'created_at' => time(),
        ]);
        $dataArr = [
            'lastId' => $lastId,
            'token' => $token,
        ];
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 通过TOKEN，获取ADMIN
     */
    public function getAdminByToken($token)
    {
        $adminLog = DB::table($this->tableLog)
            ->where('token',$token)
            ->orderBy('id','desc')->first();
        if (!$adminLog) {
            return array('code'=>-1, 'msg'=>'没有登陆');
        }
        $adminId = $adminLog->admin;
        $adminOne = DB::table($this->table)
            ->where('id',$adminId)
            ->orderBy('id','desc')->first();
        if (!$adminOne) {
            return array('code'=>-1, 'msg'=>'管理员不存在');
        }
        $dataArr = $this->getArrByObj($adminOne);
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
    }

    /**
     * 更新昵称
     */
    public function setNickname($adminId,$name)
    {
        $adminOne = DB::table($this->table)
            ->where('id',$adminId)
            ->orderBy('id','desc')->first();
        if (!$adminOne) {
            return array('code'=>-1, 'msg'=>'管理员不存在');
        }
        $resUpdate = DB::table($this->table)->where('id',$adminId)
            ->update(['name'=>$name]);
        if (!$resUpdate) {
            return array('code'=>-2, 'msg'=>'更新失败');
        }
        return true;
    }

    /**
     * 更新
     */
    public function setUpdate($adminId,$name,$pwd,$genre)
    {
        $adminOne = DB::table($this->table)->where('id',$adminId)->first();
        if (!$adminOne) {
            return array('code'=>-2, 'msg'=>'管理员不存在');
        }
        //开启事务
        DB::beginTransaction();
        try {
            $resUpdate = DB::table($this->table)->where('id',$adminId)
                ->update([
                    'name' => $name,
                    'genre' => $genre,
                    'password' => $pwd,
                    'updated_at' => time(),
                ]);
            $dataArr = array(
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 对象转数组
     */
    public function getArrByObj($adminOne)
    {
        $genres = $this->getGenres();
        $genreName = array_key_exists($adminOne->genre,$genres) ?
            $genres[$adminOne->genre] : '';
        //登陆时间
        $log = DB::table($this->tableLog)->where('admin',$adminOne->id)
            ->orderBy('id','desc')->first();
        $logTime = $log ? $log->created_at : $adminOne->created_at;
        $createTime = $logTime ? date('Y-m-d',$logTime) : '未定义';
        return [
            'adminId' => $adminOne->id,
            'adminName' => $adminOne->name,
            'genre' => $adminOne->genre,
            'genreName' => $genreName,
            'head' => $adminOne->head,
            'createTime' => $createTime,
        ];
    }
}